package org.linloong.utils;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;

public class Base64ToImage {

    public static String convertAndSave(String base64String) throws IOException {
        // 确定图片格式（可以根据扩展名判断）
        String format = getImageFormatFromBase64(base64String); // 默认格式

        String outputPath = FileUtil.getTmpDirPath() + File.separator + IdWorker.get32UUID() + "." + format;
        // 去除Base64字符串中的前缀（如 data:image/png;base64,）
        if (base64String.startsWith("data:")) {
            base64String = base64String.substring(base64String.indexOf(",") + 1);
        }

        // 解码Base64字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64String);

        // 将字节数据读取为BufferedImage对象
        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
        BufferedImage image = ImageIO.read(bis);

        // 获取输出路径并创建父目录（如果不存在）
        Path path = Paths.get(outputPath);
        Files.createDirectories(path.getParent());


        int dotIndex = outputPath.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < outputPath.length() - 1) {
            format = outputPath.substring(dotIndex + 1).toLowerCase();
        }

        // 写入图片文件
        File outputFile = new File(outputPath);
        ImageIO.write(image, format, outputFile);

        return outputPath;
    }

    public static String getImageFormatFromBase64(String base64String) {
        if (base64String.startsWith("data:image/")) {
            // 提取格式信息，如 data:image/png;base64,...
            String prefix = base64String.substring(11, base64String.indexOf(";"));
            return prefix.toLowerCase(); // 返回 "png", "jpeg", "gif" 等
        }
        return "png"; // 默认格式
    }

//    public static void main(String[] args) throws IOException {
//        String json = FileUtil.readString("C:\\Users\\kangw\\Desktop\\response.json", Charset.defaultCharset());
//        JSONObject result = JSON.parseObject(json);
//        String imageBase64 = result.getString("result_image_base64");
//        convertAndSave(imageBase64);
//    }
}
